import { Request, Response } from 'express';
import * as fs from 'fs';

export const isEmpty = (val: any) => {
  if (Array.isArray(val)) {
    return val.length === 0;
  }
  return [null, undefined, ''].includes(val);
};

export default {
  // 支持值为 Object 和 Array
  'GET /api/indicatorList': async (req: Request, res: Response) => {
    console.log('请求参数mock/indicator', req.query);
    const { name, code, type } = req.query as unknown as INDICATOR.IndicatorParams;
    const indcatorListStr = fs.readFileSync('./mock/database/indicators.json', 'utf-8');
    if (!indcatorListStr) {
      res.send({
        success: true,
        data: [],
      });
      return;
    }

    let resIndicatorList: INDICATOR.IndicatorList[] = [];
    const indicatorList: INDICATOR.IndicatorList[] = JSON.parse(indcatorListStr);
    resIndicatorList = indicatorList.filter((item) => {
      const isSearchName = name ? item.name.indexOf(name) > -1 : true;
      const isSearchCode = code ? item.code.indexOf(code) > -1 : true;
      const isSearchType = type ? item.type === type : true;
      return isSearchName && isSearchCode && isSearchType;
    });

    res.send({
      success: true,
      data: resIndicatorList,
    });
  },
  'POST /api/indicator': (req: Request, res: Response) => {
    console.log('请求参数mock/indicator', req.body);
    const { computed, ...restIndicator } = req.body as unknown as INDICATOR.IndicatorEditParams;
    if (!restIndicator.name) {
      res.send({
        data: null,
        errorMessage: '指标名称不可为空！',
        success: false,
      });
      return;
    }

    if (!restIndicator.code) {
      res.send({
        data: null,
        errorMessage: '指标编码不可为空！',
        success: false,
      });
      return;
    }

    if (isEmpty(computed)) {
      res.send({
        data: null,
        errorMessage: '计算依赖指标项不可为空！',
        success: false,
      });
      return;
    } else {
      if (computed.some((item) => isEmpty(item.name) || isEmpty(item.code))) {
        res.send({
          data: null,
          errorMessage: '计算依赖指标项中指标名称或指标编码不可为空！',
          success: false,
        });
        return;
      }
    }
    /* 设置指标默认值 */
    restIndicator.type ||= '3';

    const indcatorListStr = fs.readFileSync('./mock/database/indicators.json', 'utf-8');
    const indicatorList: INDICATOR.IndicatorList[] = indcatorListStr
      ? JSON.parse(indcatorListStr)
      : [];

    if (
      indicatorList.some(
        (item) => item.code === restIndicator.code || item.name === restIndicator.name,
      )
    ) {
      // 处理新增指标与已有指标冲突的情况
      res.send({
        data: null,
        errorMessage: '新增指标名称或编码已存在，请重新设置！',
        success: false,
      });
      return;
    }

    indicatorList.push({
      ...restIndicator,
      computed,
    });

    fs.writeFileSync('./mock/database/indicators.json', JSON.stringify(indicatorList));

    res.send({
      success: true,
      data: indicatorList,
    });
  },
  'PUT /api/indicator': (req: Request, res: Response) => {
    console.log('请求参数mock/indicator', req.body);
    const { computed, ...restIndicator } = req.body as unknown as INDICATOR.IndicatorEditParams;
    if (!restIndicator.name) {
      res.send({
        data: null,
        errorMessage: '指标名称不可为空！',
        success: false,
      });
      return;
    }

    if (!restIndicator.code) {
      res.send({
        data: null,
        errorMessage: '指标编码不可为空！',
        success: false,
      });
      return;
    }

    console.log(132, restIndicator.type, isEmpty(computed));
    if (restIndicator.type == '3' && isEmpty(computed)) {
      console.log(133);

      res.send({
        data: null,
        errorMessage: '计算依赖指标项不可为空！',
        success: false,
      });
      return;
    } else if (restIndicator.type == '3' && !isEmpty(computed)) {
      if (computed.some((item) => isEmpty(item.name) || isEmpty(item.code))) {
        res.send({
          data: null,
          errorMessage: '计算依赖指标项中指标名称或指标编码不可为空！',
          success: false,
        });
        return;
      }
    }

    const indcatorListStr = fs.readFileSync('./mock/database/indicators.json', 'utf-8');
    const indicatorList: INDICATOR.IndicatorList[] = indcatorListStr
      ? JSON.parse(indcatorListStr)
      : [];

    const editIndex = indicatorList.findIndex((item) => item.code === restIndicator.code);
    if (editIndex >= 0) {
      Object.assign(indicatorList[editIndex], req.body);
      fs.writeFileSync('./mock/database/indicators.json', JSON.stringify(indicatorList));
      res.send({
        success: true,
        data: indicatorList,
      });
    } else {
      res.send({
        data: null,
        errorMessage: '该指标编码不存在！',
        success: false,
      });
    }
  },
  'DELETE /api/indicator': (req: Request, res: Response) => {
    console.log('请求参数mock/indicator', req.body);
    const { code } = req.body as unknown as Pick<INDICATOR.IndicatorBaseType, 'code'>;

    if (!code) {
      res.send({
        data: null,
        errorMessage: '指标编码不可为空！',
        success: false,
      });
      return;
    }

    const indcatorListStr = fs.readFileSync('./mock/database/indicators.json', 'utf-8');
    const indicatorList: INDICATOR.IndicatorList[] = indcatorListStr
      ? JSON.parse(indcatorListStr)
      : [];

    const delIndex = indicatorList.findIndex((item) => item.code === code);

    if (delIndex >= 0) {
      if (indicatorList[delIndex].type !== '3') {
        res.send({
          data: null,
          errorMessage: '只能删除自定义指标 ！',
          success: false,
        });
        return;
      }
      indicatorList.splice(delIndex, 1);
      fs.writeFileSync('./mock/database/indicators.json', JSON.stringify(indicatorList));
      res.send({
        success: true,
        data: null,
      });
    } else {
      res.send({
        data: null,
        errorMessage: '该指标编码不存在！',
        success: false,
      });
    }
  },
};
